<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    {% load static %}
    <link href="{% static 'bootstrap-3.3.7-dist/css/bootstrap.min.css' %}" rel="stylesheet">
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <script src="{% static 'bootstrap-3.3.7-dist/js/bootstrap.min.js' %}"></script>
</head>
<body>
<div class="container-fluid">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <h1 class="text-center">注册页面</h1>
            <form id="myform">
                {% csrf_token %}
                {% for form in form_obj %}
                    <div class="form-group">
                        <label for="{{ form.auto_id }}">{{ form.label }}</label>
                        {{ form }}
                        <span style="color: red" class="pull-right"></span>
                    </div>
                {% endfor %}
                <div class="form-group">
                    <label for="myfile">头像
                        <img src="{% static 'img/default.png' %}" alt="头像" style="padding-left: 10px" width="80px" id="myimg">
                    </label>
                    <input type="file" name="avatar" id="myfile" style="display: none">
                </div>
                <div class="form-group">
                    <input type="button" class="btn btn-primary pull-right" value="注册" id="id_commit">
                </div>
            </form>
        </div>
    </div>
</div>
<script>
    $('#myfile').change(function () {
        let myFileReaderObj = new FileReader();
        let fileobj = $(this)[0].files[0];
        myFileReaderObj.readAsDataURL(fileobj);
        myFileReaderObj.onload=function () {
            $('#myimg').attr('src', myFileReaderObj.result)
        }
    });

    $('#id_commit').click(function () {
        let formData_obj = new FormData();
        $.each($('#myform').serializeArray(), function (index, obj) {
            console.log(index);
            formData_obj.append(obj.name, obj.value)
        });
        formData_obj.append('avatar', $('#myfile')[0].files[0]);

        $.ajax({
            url:'',
            type: 'post',
            data: formData_obj,
            contentType: false,
            processData: false,
            success: function (args) {
                if(args.code === 1000){
                    window.location.href = args.url
                }else{
                    console.log(args.msg);
                    $.each(args.msg, function (index, obj) {
                        console.log(index)
                        let targetId = '#id_' + index;
                        $(targetId).next().text(obj[0]).parent().addClass('has-error')
                    })
                }
            }
        })
    })

    $('input').focus(function () {
        $(this).next().text('').parent().removeClass('has-error')
    })
</script>
</body>
</html>